package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.*;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Department;
import com.fuershiye.woman.monitor.model.FormsDepart;
import com.fuershiye.woman.monitor.service.AreaService;
import com.fuershiye.woman.monitor.service.DepartmentService;
import com.fuershiye.woman.monitor.service.FormsDepartService;
import com.fuershiye.woman.monitor.service.FormsService;
import com.fuershiye.woman.monitor.utils.DateFormatUtil;
import com.fuershiye.woman.monitor.utils.MyUtilString;
import com.fuershiye.woman.monitor.utils.ObjectUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping(value = "/forms/depart")
public class FormsDepartController {
	
	private static final Logger logger = LoggerFactory.getLogger(FormsDepartController.class);
	
    @Autowired
    FormsDepartService formsDepartService;
    @Autowired
    AreaService areaService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    FormsService formsService;


//    @RequiresPermissions("formsDepart:view")
    @RequestMapping(value="/view.do")
    public String view(String show, Model model){

		List<Integer> years = DateFormatUtil.getAreaYears();
		model.addAttribute("years", years);

		List<IdName> formes = formsService.getAllNames();
		// 表 forms 的ID ： 1:妇儿 2:社会
		model.addAttribute("formes", formes);
//
		//部门的id
		List<IdNameSname> departmentList = departmentService.getAllSnames();
		model.addAttribute("departmentes", departmentList);

		model.addAttribute("areaList", areaService.getAllNames());
//		Area area = areaService.findByCode(CodeName.PROVINCE);
//		if(area!=null){
//			List<IdNamePid> areaList = Lists.newArrayList();
//			IdNamePid idNamePid = new IdNamePid();
//			idNamePid.setId(area.getId());
//			idNamePid.setName(area.getName());
//			idNamePid.setPid(area.getPid());
//			areaList.add(idNamePid);
//			areaList.addAll(areaService.getByLevelAndPid(null, area.getId()));
//
//			model.addAttribute("areaList", areaList);
//		}
    	
        return "forms/" + show;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
//	@RequiresPermissions("formsDepart:list")
    @RequestMapping(value="/list.do")
    @ResponseBody
    public Result list(Long areaid, Long formid, Integer year, Integer page, Integer pageSize) {

    	if(areaid==null||areaid==0 || !DateFormatUtil.isYear(year) || formid==null||formid==0){
    		logger.error("FormsDepartController list:"
    				+",areaid:"+areaid
    				+",year:"+year
    				+",formid:"+formid);

			return new Result(Massage.ERROR_PARAMETER);
    	}
		List<Integer> years = Lists.newArrayList();
		years.add(year);
    	List<FormsDepart> formsDepartList = formsDepartService.listByCondtionStatusOppositeAreaid(areaid, years, formid, 0, new Page(page, pageSize));

    	int count = formsDepartService.countByCondtionStatusOppositeAreaid(areaid, formid, year, 0);
    	
    	List<ViewFormsDepart> result = Lists.newArrayList();
    	for(FormsDepart formsDepart : formsDepartList){
    		result.add(ObjectUtil.getFormsDepart2View(formsDepart));
    	}
		
    	return new Result(Massage.SUCCESS, new PageResult(result, count));
    }

	//    @RequiresPermissions("formsDepart:save")
	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public Result save(Long id, Long formid, Integer year, Long departid, String editor) {

		if(formid==null||formid==0 || !DateFormatUtil.isYear(year) || departid==null||departid==0){
			logger.error("FormsDepartController save formsDepart:save:"
					+",formid:"+formid
					+",year:"+year
					+",departid:"+departid);

			return new Result(Massage.ERROR_PARAMETER);
		}

		boolean add = true;

		Department department = departmentService.get(departid);
		if(department==null){
			logger.error("FormsDepartController department is null, departid={}",departid);
			return new Result(Massage.DEPART_IS_NULL);
		}

		FormsDepart formsDepart =null;
		//用户想更新数据
		if(id != null && id != 0){
			//根据 ID 查询结果
			formsDepart = formsDepartService.get(id);
			if(formsDepart==null){
				logger.error("FormsDepartController update,FormsDepart is null");
				return new Result(Massage.REPORT_FORM_DEPART_NULL);
			}
		}else{
			//根据索引查询结果
			formsDepart = formsDepartService.findExist(departid, formid, year);
		}

		if(formsDepart!=null){
			add = false;
			//0:删除(默认),1:未上报(一个指标都没有上报);2:上报中(部分上报);3:审核(自己审核);4:审核(上级部门);5:审核通过(不允许修改);6:其他;
			if(formsDepart.getStatus()>1){
				return new Result(Massage.REPORT_MODIFY);
			}
		}

		if(formsDepart==null){
			formsDepart = new FormsDepart();
		}
		formsDepart.setStatus(1);
		formsDepart.setFormsid(formid);
		formsDepart.setYear(year);
		formsDepart.setDepartid(departid);
		formsDepart.setAreaid(department.getArea());
		formsDepart.setDname(department.getName());
		formsDepart.setMtime(new Date());
		if (!StringUtils.isEmpty(editor)){
			formsDepart.setEditor(editor);
		}else{
			formsDepart.setEditor(SecurityUtils.getSubject().getPrincipal() + "");
		}

		//如果是新加的则给默认的排序号sort(主键id)
		if(add){
			formsDepart.setCtime(new Date());
			if (!StringUtils.isEmpty(editor)){
				formsDepart.setMaker(editor);
			}else{
				formsDepart.setMaker(SecurityUtils.getSubject().getPrincipal() + "");
			}
		}
		formsDepartService.save(formsDepart);

		return new Result(Massage.SUCCESS);
	}

	//    @RequiresPermissions("formsDepart:save")
	@SuppressWarnings({ "rawtypes" })
	@RequestMapping(value = "/save/all.do")
	@ResponseBody
	public Result depart(Long formid, Integer year, String departids, String editor) {

		if(formid==null||formid==0 || !DateFormatUtil.isYear(year) || org.apache.commons.lang3.StringUtils.isEmpty(departids)){
			logger.error("FormsDepartController save formsDepart:save:"
					+",formid:"+formid
					+",year:"+year
					+",departids:"+departids);
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Long> departidList = MyUtilString.str2LongByPlaceHolder(departids, ",");
		for (Long departid:departidList) {
			if(departid==null){
				continue;
			}

			Department department = departmentService.get(departid);
			if(department==null){
				logger.error("FormsDepartController department is null, departid={}",departid);
				return new Result(Massage.DEPART_IS_NULL);
			}

			//根据索引查询结果
			FormsDepart formsDepart = formsDepartService.findExist(departid, formid, year);
			if(formsDepart!=null && formsDepart.getStatus()>1){
				// 0:删除(默认),1:未上报(一个指标都没有上报);
				// 2:上报中(部分上报);3:审核(自己审核);4:审核(上级部门);
				// 5:审核通过(不允许修改);6:其他;
//				return new Result(Massage.REPORT_MODIFY);
				continue;
			}

			if(formsDepart==null){
				formsDepart = new FormsDepart();
			}
			formsDepart.setStatus(1);
			formsDepart.setFormsid(formid);
			formsDepart.setYear(year);
			formsDepart.setDepartid(departid);
			formsDepart.setAreaid(department.getArea());
			formsDepart.setDname(department.getName());
			formsDepart.setCtime(new Date());
			formsDepart.setMtime(new Date());
			if (!StringUtils.isEmpty(editor)){
				formsDepart.setEditor(editor);
				formsDepart.setMaker(editor);
			}else{
				formsDepart.setEditor(SecurityUtils.getSubject().getPrincipal() + "");
				formsDepart.setMaker(SecurityUtils.getSubject().getPrincipal() + "");
			}
			formsDepartService.save(formsDepart);
		}
		return new Result(Massage.SUCCESS);
	}

//    @RequiresPermissions("formsDepart:delete")
    @RequestMapping(value="/delete.do")
    @ResponseBody
    public boolean delete(Long id) {
    	if(id==null){
    		return false;
    	}
    	FormsDepart it = formsDepartService.get(id);
    	if(it!=null){
    		formsDepartService.delete(id);
    	}
        return true;
    }

	@SuppressWarnings({ "unchecked", "rawtypes" })
//	@RequiresPermissions("formsDepart:list")
	@RequestMapping(value="/query/unset.do")
	@ResponseBody
	public Result unset(Long areaid, Long formid, Integer year) {

		if(areaid==null||areaid==0 || !DateFormatUtil.isYear(year) || formid==null||formid==0){
			logger.error("FormsDepartController unset:"
					+",areaid:"+areaid
					+",year:"+year
					+",formid:"+formid);

			return new Result(Massage.ERROR_PARAMETER);
		}
		List<Integer> years = Lists.newArrayList();
		years.add(year);
		List<FormsDepart> formsDepartList = formsDepartService.listByCondtionStatusOppositeAreaid(areaid, years, formid, 0, null);
		List<IdNameSname> departments = departmentService.getAllByLevelAndArea(null, areaid, 1);

		Set<IdNameSname> exits = Sets.newHashSet();
		for (IdNameSname idNameSname : departments) {
			loop:for(FormsDepart formsDepart : formsDepartList){
				if(idNameSname.getId().equals(formsDepart.getDepartid())){
					exits.add(idNameSname);
					break loop;
				}
			}
		}

		Set<IdNameSname> result = Sets.newHashSet();
		for (IdNameSname idNameSname : departments) {
			if(exits.add(idNameSname)){
				result.add(idNameSname);
			}
		}

		return new Result(Massage.SUCCESS, result);
	}

}
